package base.java.security;

import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import base.java.security.bean.User;
import base.java.security.bean.UserInfo;


public class UserDetailsSerivceImpl implements UserDetailsService {
	
	public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException, DataAccessException {
        UserDetails user=new User();
        GrantedAuthority[] authorities = getAuthorities( username ) ;
        //从Database里面获取user 
        String pwd = getPassword(username);
        User u =  new User();
        u.setUsername( username );
        u.setPassword( pwd );
        u.setAuthorities( authorities );
        u.setUserInfo( getUserInfo() ) ;
        user = u ;
        
		return user;
	}
	
	
	private GrantedAuthority[] getAuthorities( String username ) {
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		if( username.equalsIgnoreCase("admin") ){
			grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
		}else if( username.equalsIgnoreCase("fukui") ){
			grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
		}
		return grantedAuthorities.toArray( new GrantedAuthority[grantedAuthorities.size()] );
	}
	
	private String getPassword(  String username ){
		String pwd = "";
		if( username.equalsIgnoreCase("admin") ){
			pwd = "admin";
		}else if( username.equalsIgnoreCase("fukui") ){
			pwd = "fukui";
		}
		return pwd ;
	}
	
	
	private UserInfo getUserInfo(){
		UserInfo userInfo = new UserInfo();
		userInfo.setAge(22);
		userInfo.setEmail("fukui@asiainfo.com");
		userInfo.setTel("13980855756");
		return userInfo ;
	}
	
}

